package io.github.talelin.latticy.controller.v1;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.github.talelin.latticy.bo.BannerWithItems;
import io.github.talelin.latticy.common.mybatis.Page;
import io.github.talelin.latticy.dto.banner.BannerDTO;
import io.github.talelin.latticy.model.BannerDO;
import io.github.talelin.latticy.service.impl.BannerServiceImpl;
import io.github.talelin.latticy.vo.CreatedVO;
import io.github.talelin.latticy.vo.DeletedVO;
import io.github.talelin.latticy.vo.PageResponseVO;
import io.github.talelin.latticy.vo.UpdatedVO;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Positive;

@RequestMapping("/v1/banner")
@RestController
@Validated
public class BannerController {

    @Resource
    private BannerServiceImpl bannerService;

    @PostMapping("")
    public CreatedVO<String> create(@RequestBody BannerDTO bannerDTO){
        BannerDO banner = new BannerDO();
        BeanUtils.copyProperties(bannerDTO,banner);
        this.bannerService.save(banner);
        return new CreatedVO<>();
    }

    @DeleteMapping("/{id}")
    public DeletedVO<String> delete(@PathVariable @Positive Long id){
        bannerService.delete(id);
        return new DeletedVO<>();
    }

    @PutMapping("/{id}")
    public UpdatedVO<String> update(@RequestBody @Validated BannerDTO dto,
                            @PathVariable @Positive Long id){
        bannerService.update(dto,id);
        return new UpdatedVO<>();
    }

    @GetMapping("/{id}")
    public BannerWithItems getWithItems(@PathVariable @Positive Long id){
        return this.bannerService.getWithItems(id);
    }

    @GetMapping("/page")
    public PageResponseVO<BannerDO> getBanners(@RequestParam(required = false,defaultValue = "0")
                           @Min(value = 0)Integer page,
                           @RequestParam(required = false,defaultValue = "10")
                           @Min(value = 1)@Max(value = 30)Integer count){
        Page<BannerDO> pager = new Page<>(page, count);
        IPage<BannerDO> paging = bannerService.getBannerPage(pager);
        return new PageResponseVO<>(paging.getTotal(), paging.getRecords(), paging.getCurrent(), paging.getSize());
    }

}
